package com.kazares.persistencia;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Vector;

/**
 *
 * @author acazares Alejandro Cazares Diaz
 */
public class DbInstance {

    private Connection conn = null;

    public synchronized Connection getInstance() throws SQLException {
        try {
            conn = conn != null && conn.isClosed() ? null : conn;
        } catch (Exception e) {
            conn = null;
        }

        if (conn == null) {
            if ((conn = new MySQLEnvConn().getInstance()) == null) {
                conn = new MySQLStdConn().getInstance();
            }
        }
        return conn;
    }

    /*
    public synchronized Vector<HashMap<String, Object>> getResult(String sql) throws SQLException {
        Vector<HashMap<String, Object>> resultados = new Vector<HashMap<String, Object>>();
        Connection c = getInstance();

        PreparedStatement pst = conn.prepareStatement(sql);
        ResultSet rs = pst.executeQuery();

        //exploración por fila
        while (rs.next()) {
            HashMap<String, Object> fila = new HashMap<String, Object>();
            //exploración por columna
            for (int x = 1; x <= rs.getMetaData().getColumnCount(); x++) {
                try {
                    fila.put(rs.getMetaData().getColumnName(x), rs.getString(x));
                } catch (Exception e) {
                    System.err.println("DBInstance::getResult segment insert to hashMap: " + e);
                }
            }
            resultados.add(fila);
        }
        c.close();
        return resultados;
    }
    
    public synchronized HashMap<String, Object> getFirstResult(String sql) throws SQLException {
        HashMap<String, Object> resultado = new HashMap<String, Object>();
        Connection c = getInstance();

        PreparedStatement pst = conn.prepareStatement(sql);
        ResultSet rs = pst.executeQuery();
        
        while (rs.next()) {            
            for (int x = 1; x <= rs.getMetaData().getColumnCount(); x++) {
                try {
                    resultado.put(rs.getMetaData().getColumnName(x), rs.getString(x));
                } catch (Exception e) {
                    System.err.println("DBInstance::getResult segment insert to hashMap: " + e);
                }
            }
            return resultado;
        }
        c.close();
        return resultado;
    }*/
}
